package com.an.vhr.task;

import com.an.vhr.bean.Employee;
import com.an.vhr.bean.MailConstants;
import com.an.vhr.bean.MailSendLog;
import com.an.vhr.service.EmployeeService;
import com.an.vhr.service.MailSendLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: an1089
 **/
@Component
public class MailSendTask {
    @Resource
    MailSendLogService mailSendLogService;
    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    EmployeeService employeeService;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailResendTask(){
        List<MailSendLog> logs = mailSendLogService.getMailSendLogsByStatus();
        logs.forEach(mailSendLog -> {
            if(mailSendLog.getCount() >= 3){
                mailSendLogService.updateMailSendLogStatus(mailSendLog.getMsgId(), MailConstants.FAILURE);
            }else{
                mailSendLogService.updateCount(mailSendLog.getMsgId(),new Date());
                Employee employee = employeeService.getEmpById(mailSendLog.getEmpId());
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,employee,new CorrelationData(mailSendLog.getMsgId()));
            }
        });
    }
}
